import React, {Component} from "react";
import {observer} from "mobx-react";
import {withRouter} from "react-router-dom";
import {Comment, Reply} from "weaver-mobile-page";
import {PhotoSwipe,Tools} from "weaver-mobile";

const getLabel = Tools.getLabel
@withRouter
@observer
export default class ReplyEditor extends Component {
    constructor(props) {
        super(props);
        this.state = {
            files: [],
            index: "",
            showImage: false,
            photoVisible: false,
            photoIndex: 0,
            photoFiles: []
        }
    }

    componentDidMount() {
        const {replyStore, location, sortid, discusstype, onReload} = this.props
        replyStore.setRoutePath(location.pathname)
        if (sortid) {
            replyStore.setSortID(sortid)
            replyStore.setDiscussType(discusstype)
        }
        replyStore.onReload = onReload
        replyStore.recordHistory(this.props.history)


        document.getElementsByTagName("body")[0].style.overflow = "hidden";

        setTimeout(() => {
            let msgArr = document.getElementsByClassName("wm-comment-content-msg");
            let imgArr = [];
            let imgArrTemp = [];
            for (let i = 0; i < msgArr.length; i++) {
                imgArrTemp = msgArr[i].querySelectorAll("img");
                for (let j = 0; j < imgArrTemp.length; j++) {
                    imgArrTemp[j].style.display = "none";
                    imgArr.push(imgArrTemp[j]);
                }
            }
            for (let k = 0; k < imgArr.length; k++) {
                this.state.files.push({url: imgArr[k].src});
                imgArr[k].onclick = () => {
                    this.onItemClick(k)
                };
            }
        }, 300);
    }

    componentWillUnmount() {
        document.getElementsByTagName("body")[0].style.overflow = "visible";
    }

    onItemClick = (index) => {
        this.setState({
            showImage: true,
            index: index
        });
    }
    renderTopContent = (data) => {
        // const reg = /\bsrc\b\s*=\s*[\'\"]?([^\'\"\s]*)[\'\"]?/ig;
        let imgArr = data.imgArr;
        let imgsArea = [];
        let keyNum = 0;
        if (imgArr.length > 0) {
            let photoFiles = [];
            let imgWidth = "";
            let x = 0;// 每行显示几张图片
            for (const imgId of imgArr) {
                let imgObj = {};
                imgObj.id = imgId;
                imgObj.name = "";
                imgObj.fileExtendName = "";
                imgObj.showDelete = false;
                imgObj.url = "/weaver/weaver.file.FileDownload?fileid=" + imgId + "";
                photoFiles.push(imgObj);
            }
            if (imgArr.length === 1) {
                imgWidth = "100%";
                let styleObj = {};
                styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[0] + "')";
                styleObj.width = imgWidth;
                styleObj.paddingBottom = imgWidth;
                imgsArea.push(<div className="proj-photo-div" key={imgArr[0] + keyNum++}>
                    <div className="proj-photo-image" style={styleObj}
                         onClick={() => this.showPhotos(0, photoFiles)}></div>
                </div>);
            } else if (imgArr.length === 2 || imgArr.length === 4) {
                x = 2;
                let rowCount = imgArr.length / x;
                for (let j = 0; j < rowCount; j++) {
                    imgWidth = "48%";
                    let imgsInner = [];
                    for (let k = j * x; k < j * rowCount + x; k++) {
                        let styleObj = {};
                        styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[k] + "')";
                        styleObj.width = imgWidth;
                        styleObj.paddingBottom = imgWidth;
                        if (j > 0) {
                            styleObj.marginTop = "3%";
                        }
                        imgsInner.push(<div className="proj-photo-image" key={imgArr[0] + keyNum++}
                                            onClick={() => this.showPhotos(k, photoFiles)} style={styleObj}></div>);
                    }
                    imgsArea.push(<div className="proj-photo-div" key={"both_" + j}>{imgsInner}</div>);
                }
            } else {
                x = 3;
                let rowCount = parseInt(imgArr.length % x === 0 ? imgArr.length / x : imgArr.length / x + 1, 10);
                for (let j = 0; j < rowCount; j++) {
                    imgWidth = "30%";
                    let imgsInner = [];
                    for (let k = j * x; k < j * x + x; k++) {
                        let styleObj = {};
                        styleObj.width = imgWidth;
                        styleObj.paddingBottom = imgWidth;
                        if (j > 0) {
                            styleObj.marginTop = "4%";
                        }
                        if (k >= imgArr.length) {
                            imgsInner.push(<div className="proj-photo-image" key={imgArr[0] + keyNum++}
                                                onClick={() => this.showPhotos(k, photoFiles)}
                                                style={styleObj}></div>);
                        } else {
                            styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[k] + "')";
                            imgsInner.push(<div className="proj-photo-image" key={imgArr[0] + keyNum++}
                                                onClick={() => this.showPhotos(k, photoFiles)}
                                                style={styleObj}></div>);
                        }
                    }
                    imgsArea.push(<div className="proj-photo-div" key={imgArr[0] + keyNum++}>{imgsInner}</div>);
                }
            }
            return <div>{imgsArea} </div>
        }


    }
    //手机端发表图片往内容最后追加
    onImgChange = (datas) => {
        let {replyStore: {imageArr}} = this.props;
        imageArr.length = 0
        datas.forEach(v => {
            imageArr.push(`<img src=${v.imgSrc} />`)
        })
    }
    showPhotos = (photoIndex, photoFiles) => {
        this.setState({
            photoFiles: photoFiles,
            photoVisible: true,
            photoIndex: photoIndex
        })
    }
    hidePhotos = () => {
        this.setState({
            photoVisible: false,
            photoIndex: 0
        })
    }

    openLink = (href) => {
        window.openLink(href);
    }

    render() {
        const {
            replyStore: {commentStore, reply, submitReply,source}
        } = this.props;
        const {files, index, showImage} = this.state;
        const leftConfig = [
            {type: "voice"},
            {type: "blog-biaoqing"},
            {type: "blog-tupian"},
            // {type: "blog-xiangce"},
            // {type: "@"},
            {type: "tianjia"},
        ];
        // const buttonGroupData = [
        //     {
        //         key: "clear",
        //         text: "取消",
        //         onClick: () => this.props.history.go(-1),
        //     },
        //     {
        //         key: "submit",
        //         text: "确定",
        //         onClick: () => this.props.history.go(-1),
        //         type: "primary",
        //     },
        // ];
        return (<div className='proj-Comment' style={{height: "100%"}}>
                <Comment
                    store={commentStore}
                    renderTopContent={this.renderTopContent}
                    renderRightTop={(v) => (
                        source?null:<div className="active-content-proj">
                                            <span onClick={(e) => {
                                                e && e.stopPropagation ? e.stopPropagation() : window.event.cancelBubble = true;
                                                if (v.type_n === "PP") {
                                                    this.props.history.push(`/ProjectDetails/0/${v.prjtaskid}/view`)
                                                } else {
                                                    this.props.history.push(`/TaskDetails/0/${v.prjtaskid}`)
                                                }
                                            }}>
                                                {v.type_n === "PP" ? <span> #【{getLabel("101", "项目")}】</span> :
                                                    <span> #【{getLabel("1332", "任务")}】</span>}
                                                {v.name}#
                                            </span>
                        </div>)}
                    operateAttachList={(type,data)=>this.openLink(data.url)}
                />
                <PhotoSwipe
                    options={{shareEl: false, tapToClose: true}}
                    items={this.state.photoFiles}
                    index={this.state.photoIndex}
                    visible={this.state.photoVisible}
                    onClose={this.hidePhotos}
                />
                {this.props.sortid ? <Reply
                    wrappedComponentRef={ref => this.replyRef = ref}
                    store={reply}
                    leftConfig={leftConfig}
                    visible={false}
                    showOutInput
                    imgUploadUrl={"/api/doc/upload/uploadFile"}
                    onImgChange={this.onImgChange}
                    onSubmit={(data) => {
                        submitReply(data, this.replyRef)
                    }}
                /> : null}
                <PhotoSwipe
                    items={files}
                    index={index}
                    visible={showImage}
                    onClose={() => this.setState({showImage: false})}
                />
                {/* <Route
                    key={layout.id}
                    path={layout.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="wmPoutePageDemo"
                                className="wm-route-layout"
                            >
                                编辑
                                <ButtonGroup data={buttonGroupData} />
                            </div>
                        </RouteLayout>
                    )}
                />*/}
            </div>
        )
    }
}


